// 登录模块

var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
const config = require('../token/config');
// 导入db ,操作数据库
const { getAll, getOne, exec } = require('../db/index');
const { isValidToken } = require('../token');

const secret = 'register-rule';
// 登录
router.post('/', async (req, res) => {
  const { user_name, user_pwd } = req.body;
  if (!user_name && !user_pwd) {
    return res.send({
      code: 100104,
      message: '参数格式不对',
      result: '用户密码不能为空',
    });
  }
  let sql = `select * from user`;
  const resData = await getAll(sql);
  // console.log(resData)
  let user = resData.map((item) => item.user_name);
  if (!user.includes(user_name)) {
    return res.send('该用户不存在');
  }
  if (user.includes(user_name)) {
    let sql2 = `select * from user where user_name='${user_name}'`;
    const dataByName = await getAll(sql2);
    let sql1 = `select user_pwd from user where user_name='${user_name}'`;
    const psw = await getAll(sql1);
    // console.log(psw)
    let sql3 = `select user_status from user where user_name='${user_name}'`;
    const sta = await getAll(sql3);
    console.log(sta[0].user_status); //拿到状态值判断是否被禁用
    // if (sta[0].user_status == 1) {
    //   console.log('启用')
    // } else {
    //   console.log('禁用')
    // }
    if (user_pwd == psw[0].user_pwd && sta[0].user_status == 1) {
      let token = jwt.sign({ user_name }, config.token.secretKey, {
        expiresIn: '24h',
      });
      return res.send({
        code: 0,
        message: '登录成功',
        result: {
          user_name,
          token,
        },
      });
    } else {
      return res.send({
        code: 1004,
        message: '密码错误或你已被禁用',
      });
    }
  }
});
// 注册
router.post('/register', async (req, res) => {
  const { user_name, user_pwd, user_type } = req.body;
  if (!user_name && !user_pwd && !user_type) {
    return res.send({
      code: 100104,
      message: '参数格式不对',
      result: '用户密码用户类型不能为空',
    });
  }
  let sql = `select * from user`;
  const resData = await getAll(sql);
  console.log(resData);
  let user = resData.map((item) => item.user_name);

  if (user.includes(user_name)) {
    return res.send('该用户已存在');
  }
  if (!user.includes(user_name)) {
    let sql = `insert into user (user_name,user_pwd, user_type)  values  ('${user_name}', '${user_pwd}','${user_type}')`;
    try {
      const data = await exec(sql);
      console.log(data);
      res.send({
        code: 0,
        message: '注册用户成功',
        result: {
          user_id: data.insertId,
          user_name,
          user_pwd,
          user_type,
        },
      });
    } catch (err) {
      res.send({
        code: 'err',
        message: '注册用户失败',
        result: debug ? '' : err,
      });
    }
  }
});

//验证token
router.post('/vertify', isValidToken);
module.exports = router;
